import Taro, { Component } from '@tarojs/taro'
import { connect } from "@tarojs/redux";
import _isEmpty from 'lodash/isEmpty'
import { View, Text } from '@tarojs/components'
import { AtIcon, AtSwitch } from 'taro-ui'
import { addAddress2book, getAddressInfo, editAddressInfo } from '@/actions/common'
import { divisionCityStr } from '@/utils'

import AddressFormInput from '../../components/AddressFormInput'
import BaseButton from '../../components/BaseButton'
import {ModalBottom} from '../../components/CustomModal'
import MultiSelectList from '../../components/MultiSelectList'

import proList from '@/utils/cityJson/province.json'
import cityJson from '@/utils/cityJson/city.json'
import disJson from '@/utils/cityJson/district.json'

import './index.scss'

@connect(({ common }) => ({
  common
}))
class AddressCreate extends Component {
  config = {
    navigationBarTitleText: '新建地址',
  }

  constructor(props) {
    super(props)
  }

  state = {
    isSend: true,
    isSave: true,
    addType: '',  // 地址薄操作 add新增 edit编辑
    linkman: '',
    mobile: '',
    extMobile: '',
    proStr: '',
    address: '',
    cityModal: false,
    cityList: [],
    disList: [],
    addInfo: {},
    tempProvince: [],
  }

  componentDidShow(){
    this.handleAddressInfo()
  }

  handleAddressInfo = () => {
    const addType = this.$router.params.type
    const user = this.$router.params.user
    const uInfo = Taro.getStorageSync(`address_info_${user}`)
    const as_info = Taro.getStorageSync('address_addselect_info')
    const add_info = Taro.getStorageSync('address_add_info')
    const edit_info = Taro.getStorageSync('address_edit_info')
    const cd = Taro.getStorageSync('map_select_city')

    this.setState({ addType })
    if(cd && !_isEmpty(cd)){
      const mArr = cd.mobile ? cd.mobile.split('-') : []
      const proStr =  (cd.provinceCn+cd.cityCn+cd.districtCn) || '';
      this.setState({ 
        isSend: user === 'sender',
        linkman: cd.linkman || '',
        mobile: mArr[0] || '',
        extMobile: mArr[1] || '',
        address: cd.address,
        proStr,
      })
    }else{
      switch (addType) {
        case 'addselect':{
          if(as_info && !_isEmpty(as_info)){
            const mArr = as_info.mobile ? as_info.mobile.split('-') : []
            const proStr =  (as_info.provinceCn+as_info.cityCn+as_info.districtCn) || '';
            this.setState({
              isSend: user === 'sender',
              linkman: as_info.linkman || '',
              mobile: mArr[0] || '',
              extMobile: mArr[1] || '',
              address: as_info.address,
              proStr
            })
          }else{
            const mArr = uInfo.mobile ? uInfo.mobile.split('-') : []
            const proStr = uInfo.provinceCn+uInfo.cityCn+uInfo.districtCn || '';
            this.setState({
              isSend: user === 'sender',
              linkman: uInfo.linkman || '',
              mobile: mArr[0] || '',
              extMobile: mArr[1] || '',
              address: uInfo.address,
              proStr
            })
          }
          
          break;
        }
        case 'add':{
          const mArr = add_info.mobile ? add_info.mobile.split('-') : []
          const proStr =  (add_info.provinceCn+add_info.cityCn+add_info.districtCn) || '';
          this.setState({
            linkman: add_info.linkman || '',
            mobile: mArr[0] || '',
            extMobile: mArr[1] || '',
            address: add_info.address,
            proStr
          })
          break;
        }
        case 'edit':{
          const mArr = edit_info.mobile ? edit_info.mobile.split('-') : []
          const proStr =  (edit_info.provinceCn + edit_info.cityCn + edit_info.districtCn) || '';
          this.setState({
            linkman: edit_info.linkman || '',
            mobile: mArr[0] || '',
            extMobile: mArr[1] || '',
            address: edit_info.address,
            proStr
          })
          break;
        }
        default:
          break;
      }
    }
  }

  componentDidMount() {
    const isSend = this.$router.params.user === 'sender'
    const aid = this.$router.params.aid
    this.setState({ isSend })
    if(aid){
      this.aid = aid
      this.getCurrentAddressInfo(aid)
    }
  }

  render() {
    const { isSend, isSave, addType, linkman, mobile, extMobile,address, proStr, cityModal, cityList, disList, tempProvince } = this.state
    const user = this.$router.params.user

    return (
      <View className="addresscreate-page">
        <View className="addresscreate-container">
          <View className="form-card">
           {addType === 'addselect' && <View className={`recipient-label ${isSend? 'send-label' : '' }`}>{isSend?'寄':'收'}件人</View>}
            <View className="addresscreate-form">
              <View className="form-item">
                <View className="form-item-box">
                  <AddressFormInput
                    label="姓名"
                    initValue={linkman || ''}
                    placeholder="请填写姓名"
                    onChange={this.linkmanInput}
                    onBlur={this.saveLinkmanInput}
                  ></AddressFormInput>
                </View>
                <View
                  className="form-item-right"
                  hoverClass="base-hover"
                  onClick={() => {
                    Taro.removeStorageSync('map_select_city')
                    Taro.navigateTo({
                      url: `/pages/addressbook/index?type=${addType}&user=${user}`
                    })
                  }}
                >地址簿</View>
              </View>
              <View className="form-item">
                <View className="form-item-box">
                  <AddressFormInput
                    label="电话"
                    initValue={mobile || ''}
                    type='number'
                    maxLength={11}
                    placeholder="请填写电话"
                    onChange={this.mobileInput}
                    onBlur={this.saveMobileInput}
                  ></AddressFormInput>
                </View>
                <View className="form-item-right is-input">
                  <AddressFormInput
                    label="一"
                    initValue={extMobile || ''}
                    type='number'
                    placeholder="分机号选填"
                    maxLength={8}
                    onChange={this.extMobileInput}
                    onBlur={this.saveExtMobileInput}
                    flexBasic={'50'}
                  ></AddressFormInput>
                </View>
              </View>
              <View className="form-item">
                <View className="form-item-box">
                  <View className='form-item-label'>
                    <Text>省市区</Text>
                    <View className={`${proStr ? 'label-text' : ''}`} onClick={() => this.handleCityModal(true)}>{proStr || '请填写省市区'}</View>
                  </View>
                </View>
                <View className="form-item-right" onClick={() => {
                  const adInfo = Taro.getStorageSync(`address_${addType}_info`)
                  if(adInfo){
                    Taro.setStorageSync('map_select_city', adInfo)
                  }else{
                    const cd = {
                      linkman,
                      mobile: `${mobile}-${extMobile}`,
                      address
                    }
                    Taro.setStorageSync('map_select_city', cd)
                  }
                  // console.log('add==', adInfo, Taro.getStorageSync('map_select_city') )
                  setTimeout(()=>{
                    Taro.removeStorageSync('address_addselect_info')
                    Taro.removeStorageSync('address_add_info')
                    Taro.removeStorageSync('address_edit_info')
                    Taro.navigateTo({
                      url: '/pages/addressselector/index'
                    })
                  })
                }}>
                  <AtIcon value="map-pin" size="13" color="#000"></AtIcon>
                </View>
              </View>
              <View className="form-item">
                <View className="form-item-box">
                  <AddressFormInput
                    label="详细地址"
                    initValue={address || ''}
                    placeholder="请填写详细地址"
                    onChange={this.addressInput}
                    onBlur={this.saveAddressInput}
                    inputType="textarea"
                  ></AddressFormInput>
                </View>
              </View>
            </View>
          </View>
         {addType === 'addselect' && <View className="switch-wrapper">
            <View className="switch-label">
              <Text>保存到地址簿</Text>
            </View>
            <View className="switch-box">
              <AtSwitch
                color="#FF5D24"
                checked={isSave}
                onChange={this.handleSaveChange}
              ></AtSwitch>
            </View>
          </View>}
          <View className="save-button-wrapper">
            <BaseButton
              text="保存"
              type='primary'
              width='100%'
              onClick={this.handleSaveAddress}
            ></BaseButton>
          </View>
        </View>
        
        {/* 省市区modal */}
        <ModalBottom 
          title='选择省市区'
          isOpened={cityModal}
          onClose={() => this.handleCityModal(false)}
        >
          <MultiSelectList fdata={proList} sdata={cityList} tdata={disList} value={tempProvince} onSelect={this.handleSelectProvince}/>
        </ModalBottom>
      </View>
    )
  }

  linkmanInput = (val) => {
    this.setState({ linkman: val })
  }


  mobileInput = (val) => {
    this.setState({ mobile: val })
  }
 

  extMobileInput = (val) => {
    this.setState({ extMobile: val })
  }


  addressInput = (val) => {
    this.setState({ address: val })
  }
 
  getCurrentAddressInfo = (aid) => {
    const { dispatch } = this.props
    dispatch(getAddressInfo(aid, (res) => {
      if(res.code >= 0){
        const ad = res.data
        const mArr = ad.mobile ? ad.mobile.split('-') : []
        let proStr = ad.provinceCn+ad.cityCn+ad.districtCn || '';
        this.setState({
          linkman: ad.linkman || '',
          mobile: mArr[0] || '',
          extMobile: mArr[1] || '',
          address: ad.address,
          proStr
        })
      }
    }))
  }

  handleCityModal = (flag) => {
    this.setState({ cityModal: !!flag })
  }

  /** 选择省市区 */
  handleSelectProvince = (val) => {
    console.log('选择城市==',val)
    this.setState({ tempProvince: val })
    if(val[0]){
      const pid = val[0].id
      if(pid){
        const cityList = cityJson[pid]
        this.setState({ 
          cityList,
          disList: []
        })
      }
    }
    if(val[1]){
      const cid = val[1].id
      if(cid){
        const disList = disJson[cid]
        this.setState({ disList })
      }
    }
    if(val.length === 3){
      if(val[0] && val[1] && val[2]){
        this.setState({
          cityModal: false,
          proStr: val[0].name+val[1].name+val[2].name
        })
      }
    }
  }

  handleSaveChange = (flag) => {
    this.setState({ isSave: !!flag })
  }

  handleSaveAddress = () => {
    console.log('保存地址')
    const { isNew, linkman, mobile, extMobile, proStr, address, isSave, isSend } = this.state
    const { dispatch } = this.props
    const user = this.$router.params.user
    const addType = this.$router.params.type
    const aid = this.$router.params.aid
    if(!linkman){
      Taro.showToast({title: '请输入联系人', icon: 'none'})
      return
    }
    if(!mobile){
      Taro.showToast({title: '请输入电话', icon: 'none'})
      return
    }
    if(!proStr){
      Taro.showToast({title: '请选择省市区', icon: 'none'})
      return
    }
    if(!address){
      Taro.showToast({title: '请输入详细地址', icon: 'none'})
      return
    }
    const proObj = divisionCityStr(proStr)
    
    if(addType ==='add'){
      const params = {
        linkman,
        mobile: extMobile ? `${mobile}-${extMobile}` : mobile,
        ...proObj,
        address
      }
      dispatch(addAddress2book(params))
    }else if(addType === 'edit'){
      const params = {
        id: aid,
        linkman,
        mobile: extMobile ? `${mobile}-${extMobile}` : mobile,
        ...proObj,
        address
      }
      dispatch(editAddressInfo(params))
    }else {
      const params = {
        type: user,
        linkman,
        mobile: extMobile ? `${mobile}-${extMobile}` : mobile,
        ...proObj,
        address
      }
      Taro.setStorageSync(`address_info_${user}`, params)
      if(isSave){
        dispatch(addAddress2book(params))
      }
    }
    
    Taro.showLoading()
    setTimeout(() => {
      Taro.hideLoading()
      Taro.navigateBack()
    }, 500);
  }

}

export default AddressCreate
